package dahlpay

import (
	"fmt"
	"errors"
	"strings"
	"crypto/md5"
	"github.com/astaxie/beego"
)

type DahlPayMsg struct {
	FlowId   string  `json:"flowid"`   // 我方的交易订单号
	Paytime  string  `json:"paytime"`  // 对账时间,yyyyMMddHHmmss
	Fee      string  `json:"fee"`      // 支付金额
	Ext      string  `json:"ext"`      // 渠道流水号
	Status   string  `json:"status"`   // 支付状态，success为成功；失败的无通知
	Sign     string  `json:"sign"`     // 数字签名
}

func MakeNotifyMd5Sign(flowid,status,appSecret string) string {
	str := fmt.Sprintf("flowid=%s&status=%s%s",flowid,status,appSecret)
	return fmt.Sprintf("%X", md5.Sum([]byte(str)))
}

func DahlPayNotify(rsp *DahlPayMsg, mchId, appKey string) (map[string]string, error){
	rspMap := make(map[string]string)
	rspMap["flowid"] = rsp.FlowId
	rspMap["paytime"] = rsp.Paytime
	rspMap["fee"] = rsp.Fee
	rspMap["ext"] = rsp.Ext
	rspMap["status"] = rsp.Status
	rspMap["sign"] = rsp.Sign
	sign := MakeNotifyMd5Sign(rsp.FlowId,rsp.Status,appKey)
	beego.Debug("sign:", sign, "rsp.Sign:", rsp.Sign)
	sign = strings.Replace(sign, " ", "", -1)
	rsp.Sign = strings.Replace(rsp.Sign, " ", "", -1)
	result := strings.EqualFold(rsp.Sign, sign)
	if  !result {
		returnMsg := "sign is invalid"
		return map[string]string{}, errors.New(returnMsg)
	}
	return rspMap, nil
}
